package com.baishancloud.log.udf.string;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * 暂时没用到
 *
 * @author wangziqiang
 * @date 2022-01-17
 */
public class SplitToArray extends ScalarFunction {

    private static final Logger LOGGER = LoggerFactory.getLogger(SplitToArray.class);

    public String[] eval(String value) {
        String[] result = new String[6];
        // 1 获取传入的数据
        try {
            if (value != null && value.length() > 0) {
                String[] split = value.split("-");
                if (value.contains(":")) {
                    ArrayUtils.reverse(split);
                    String ip = split[0].replace("::", ".").replace(":", "");
                    String cabinet = split[1];
                    String city = split[2];
                    String province = split[3];
                    String[] isp = new String[split.length - 4];
                    System.arraycopy(split, 4, isp, 0, split.length - 4);
                    String s = Arrays.toString(isp);
                    String replace = s.replace("[", "").replace("]", "");

                    result[0] = city + "-" + ip;
                    result[1] = ip;
                    result[2] = cabinet;
                    result[3] = city;
                    result[4] = province;
                    result[5] = replace;
                } else {
                    // 2 将string转换为json数组
                    ArrayUtils.reverse(split);
                    String ip = split[3] + "." + split[2] + "." + split[1] + "." + split[0];
                    String cabinet = split[4];
                    String city = split[5];
                    String province = split[6];
                    String[] isp = new String[split.length - 7];
                    System.arraycopy(split, 7, isp, 0, split.length - 7);
                    String s = Arrays.toString(isp);
                    String replace = s.replace("[", "").replace("]", "");

                    result[0] = city + "-" + ip;
                    result[1] = ip;
                    result[2] = cabinet;
                    result[3] = city;
                    result[4] = province;
                    result[5] = replace;
                }
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.stringifyException(e));
        }
        return result;
    }


}

